package com.webex.ta.hydra.core;

import com.webex.ta.hydra.util.HydraUtils;

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-30
 * Time: 13:26:44
 */
public class PropertyManager {
    private static PropertyManager instance;

    private Properties system = new Properties();
    private Properties user = new Properties();
    private List<Properties> plugins = new LinkedList<Properties>();

    private PropertyManager() {}

    public static PropertyManager getInstance() {
        if (instance == null) {
            instance = new PropertyManager();
            instance.loadSystemProps();
            instance.loadUserProps();
        }
        return instance;
    }

    public void loadSystemProps() {
        loadProps(system, this.getClass().getResourceAsStream(
				"/com/webex/ta/hydra/resources/hydra.properties"));
        loadProps(system, this.getClass().getResourceAsStream(
				"/com/webex/ta/hydra/hydra_gui.properties"));
    }

    public void loadUserProps() {
        try {
            loadProps(user, new FileInputStream(HydraUtils.getHydraBinPath() + File.separator + "preference.properties"));
        } catch (FileNotFoundException ignore) {
        }
    }

    public void saveUserProps() {
        try {
            user.store(new FileOutputStream("preference.properties"),"Hydra user preference");
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
    }

    public void setUserProperty(String key, String value) {
        user.setProperty(key, value);
    }

    public void addPluginProps(Properties props) {
		plugins.add(props);
	}

    public String getProperty(String name) {
        return getProperty(name, null);
    }

    public String getProperty(String name, String defaultValue) {
        for (Properties plugin : plugins) {
            if (plugin.getProperty(name) != null)
                return plugin.getProperty(name);
        }
        String value = user.getProperty(name);
        if (value != null)
            return value;

        return system.getProperty(name, defaultValue);
    }

//    public void loadPluginProps(InputStream in) {
//		Properties plugin = new Properties();
//		loadProps(plugin,in);
//		plugins.add(plugin);
//	}

    private static void loadProps(Properties into, InputStream in) {
        try {
            into.load(in);
        } catch(IOException ignore) {

        } finally {
            HydraUtils.closeQuietly(in);
        }
    }
}
